/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CvsTreeView.java
 *
 * Created on 2010-12-9, 16:10:56
 */
package net.labthink.cvs;

import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import net.labthink.utils.FilePlus;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.sun.java.swing.plaf.windows.WindowsTreeUI.WindowsTreeCellRenderer;

/**
 *
 * @author Mosliu
 */
public class CvsTreeView extends javax.swing.JFrame {

    private static final String STORE_FILE = "config.dat";

    /** Creates new form CvsTreeView */
    public CvsTreeView() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu_treemenu = new javax.swing.JPopupMenu();
        jMenuItem_openFolder = new javax.swing.JMenuItem();
        jMenuItem_newFolder = new javax.swing.JMenuItem();
        jToolBar_menu = new javax.swing.JToolBar();
        jTextField_cvsrootfolder = new javax.swing.JTextField();
        jButton_find = new javax.swing.JButton();
        jButton_go = new javax.swing.JButton();
        jSplitPane_holder = new javax.swing.JSplitPane();
        jScrollPane_jtree = new javax.swing.JScrollPane();
        jTree_folderlist = new javax.swing.JTree();
        jPanel_properties = new javax.swing.JPanel();
        jTabbedPane_xmlcontent = new javax.swing.JTabbedPane();
        jScrollPane_xmlcontent = new javax.swing.JScrollPane();
        jTextArea_xmlcontent = new javax.swing.JTextArea();
        jPanel_table = new javax.swing.JPanel();
        jScrollPane_table = new javax.swing.JScrollPane();
        jTable_test = new javax.swing.JTable();
        jPanel_tableControl = new javax.swing.JPanel();
        jButton_insertRow = new javax.swing.JButton();
        jButton_deleteRow = new javax.swing.JButton();
        jButton_clear = new javax.swing.JButton();
        jButton_save = new javax.swing.JButton();

        jMenuItem_openFolder.setText("打开目录");
        jMenuItem_openFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem_openFolderActionPerformed(evt);
            }
        });
        jPopupMenu_treemenu.add(jMenuItem_openFolder);

        jMenuItem_newFolder.setText("新建目录");
        jMenuItem_newFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem_newFolderActionPerformed(evt);
            }
        });
        jPopupMenu_treemenu.add(jMenuItem_newFolder);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jToolBar_menu.setRollover(true);

        jTextField_cvsrootfolder.setText("F:\\CVSROOT");
        jToolBar_menu.add(jTextField_cvsrootfolder);

        jButton_find.setText("...");
        jButton_find.setToolTipText("转到目录");
        jButton_find.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jButton_find.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton_find.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_findActionPerformed(evt);
            }
        });
        jToolBar_menu.add(jButton_find);

        jButton_go.setText("转到");
        jButton_go.setToolTipText("转到目录");
        jButton_go.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jButton_go.setFocusable(false);
        jButton_go.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton_go.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton_go.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_goActionPerformed(evt);
            }
        });
        jToolBar_menu.add(jButton_go);

        jSplitPane_holder.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jSplitPane_holder.setDividerLocation(300);

        jScrollPane_jtree.setBorder(javax.swing.BorderFactory.createTitledBorder("CVS目录选择"));
        jScrollPane_jtree.setViewportBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jScrollPane_jtree.setAutoscrolls(true);

        jTree_folderlist.setLargeModel(true);
        jTree_folderlist.setMaximumSize(new java.awt.Dimension(200, 300));
        jTree_folderlist.setPreferredSize(null);
        jTree_folderlist.setVisibleRowCount(17);
        jTree_folderlist.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTree_folderlistMouseClicked(evt);
            }
        });
        jScrollPane_jtree.setViewportView(jTree_folderlist);

        jSplitPane_holder.setLeftComponent(jScrollPane_jtree);

        jPanel_properties.setBorder(javax.swing.BorderFactory.createTitledBorder("属性"));

        jTabbedPane_xmlcontent.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jTabbedPane_xmlcontentStateChanged(evt);
            }
        });

        jTextArea_xmlcontent.setColumns(20);
        jTextArea_xmlcontent.setRows(5);
        jTextArea_xmlcontent.setBorder(null);
        jScrollPane_xmlcontent.setViewportView(jTextArea_xmlcontent);

        jTabbedPane_xmlcontent.addTab("XML内容", jScrollPane_xmlcontent);

        jTable_test.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "All", "Deny", "Read", "Write", "Tag", "Create", "Control"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable_test.setFillsViewportHeight(true);
        jTable_test.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable_test.getTableHeader().setReorderingAllowed(false);
        jTable_test.getColumnModel().getColumn(0).setPreferredWidth(200);
        jTable_test.getColumnModel().getColumn(1).setPreferredWidth(35);
        jTable_test.getColumnModel().getColumn(2).setPreferredWidth(40);
        jTable_test.getColumnModel().getColumn(3).setPreferredWidth(40);
        jTable_test.getColumnModel().getColumn(4).setPreferredWidth(50);
        jTable_test.getColumnModel().getColumn(5).setPreferredWidth(60);
        jTable_test.getColumnModel().getColumn(6).setPreferredWidth(35);
        jTable_test.getColumnModel().getColumn(7).setPreferredWidth(60);
        jScrollPane_table.setViewportView(jTable_test);

        jButton_insertRow.setText("Insert");
        jButton_insertRow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_insertRowActionPerformed(evt);
            }
        });

        jButton_deleteRow.setText("Delete");
        jButton_deleteRow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_deleteRowActionPerformed(evt);
            }
        });

        jButton_clear.setText("Clear");
        jButton_clear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_clearActionPerformed(evt);
            }
        });

        jButton_save.setText("Save");
        jButton_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_saveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel_tableControlLayout = new javax.swing.GroupLayout(jPanel_tableControl);
        jPanel_tableControl.setLayout(jPanel_tableControlLayout);
        jPanel_tableControlLayout.setHorizontalGroup(
            jPanel_tableControlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_tableControlLayout.createSequentialGroup()
                .addComponent(jButton_insertRow)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton_deleteRow)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton_clear)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton_save)
                .addContainerGap(401, Short.MAX_VALUE))
        );
        jPanel_tableControlLayout.setVerticalGroup(
            jPanel_tableControlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_tableControlLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton_insertRow)
                .addComponent(jButton_deleteRow)
                .addComponent(jButton_clear)
                .addComponent(jButton_save))
        );

        javax.swing.GroupLayout jPanel_tableLayout = new javax.swing.GroupLayout(jPanel_table);
        jPanel_table.setLayout(jPanel_tableLayout);
        jPanel_tableLayout.setHorizontalGroup(
            jPanel_tableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel_tableControl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane_table, javax.swing.GroupLayout.DEFAULT_SIZE, 677, Short.MAX_VALUE)
        );
        jPanel_tableLayout.setVerticalGroup(
            jPanel_tableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel_tableLayout.createSequentialGroup()
                .addComponent(jScrollPane_table, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel_tableControl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jTabbedPane_xmlcontent.addTab("权限控制", jPanel_table);

        javax.swing.GroupLayout jPanel_propertiesLayout = new javax.swing.GroupLayout(jPanel_properties);
        jPanel_properties.setLayout(jPanel_propertiesLayout);
        jPanel_propertiesLayout.setHorizontalGroup(
            jPanel_propertiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane_xmlcontent, javax.swing.GroupLayout.DEFAULT_SIZE, 682, Short.MAX_VALUE)
        );
        jPanel_propertiesLayout.setVerticalGroup(
            jPanel_propertiesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane_xmlcontent, javax.swing.GroupLayout.DEFAULT_SIZE, 667, Short.MAX_VALUE)
        );

        jSplitPane_holder.setRightComponent(jPanel_properties);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jSplitPane_holder, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 1004, Short.MAX_VALUE)
                    .addComponent(jToolBar_menu, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 1004, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar_menu, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane_holder, javax.swing.GroupLayout.DEFAULT_SIZE, 698, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_insertRowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_insertRowActionPerformed
       //        jTable_test.getColumnModel().getColumn(0).setWidth(300);
//        jTable_test.getColumnModel().getColumn(0).setPreferredWidth(200);
//        jTable_test.getColumnModel().getColumn(1).setPreferredWidth(35);
//        jTable_test.getColumnModel().getColumn(2).setPreferredWidth(40);
//        jTable_test.getColumnModel().getColumn(3).setPreferredWidth(40);
//        jTable_test.getColumnModel().getColumn(4).setPreferredWidth(50);
//        jTable_test.getColumnModel().getColumn(5).setPreferredWidth(60);
//        jTable_test.getColumnModel().getColumn(6).setPreferredWidth(35);
//        jTable_test.getColumnModel().getColumn(7).setPreferredWidth(60);
        DefaultTableModel model = (DefaultTableModel) jTable_test.getModel();
        Object[] a = {"", false, false, false, false, false, false, false};
        model.addRow(a);
    }//GEN-LAST:event_jButton_insertRowActionPerformed

    private void jButton_findActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_findActionPerformed
//        JOptionPane.showConfirmDialog(jSplitPane1, "本功能暂未实现，留待下一版本想起来再说");
        JFileChooser jfc = new JFileChooser();
        jfc.setDialogTitle("打开CVS仓库目录");
        jfc.setMultiSelectionEnabled(false);
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int result = jfc.showOpenDialog(this);  // 打开"打开文件"对话框
        if (result == JFileChooser.APPROVE_OPTION) {
            String path = jfc.getSelectedFile().getAbsolutePath();
            jTextField_cvsrootfolder.setText(path);
        }
        jButton_goActionPerformed(evt);
    }//GEN-LAST:event_jButton_findActionPerformed

	private void jButton_goActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_goActionPerformed
            String rootdir = jTextField_cvsrootfolder.getText();
            File f_rootdir = new File(rootdir);
//            JOptionPane.showConfirmDialog(jSplitPane1, "本功能暂未实现，留待下一版本想起来再说");
            DefaultTreeModel model = (DefaultTreeModel) jTree_folderlist.getModel();
            DefaultMutableTreeNode rootnode = new DefaultMutableTreeNode(f_rootdir);
            fillFileNode(f_rootdir, rootnode);
            model.setRoot(rootnode);
    }//GEN-LAST:event_jButton_goActionPerformed
    private void jTree_folderlistMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTree_folderlistMouseClicked
//        System.out.println(evt.getComponent().toString());
//        System.out.println("单击" + evt.getClickCount() + "次");
//        System.out.println(evt.getButton());
        if (evt.getButton() != 1) {
            if (evt.getButton() == 3) {
                //右键，打开目录。
                TreePath path = jTree_folderlist.getPathForLocation(evt.getX(), evt.getY()); // 关键是这个方法的使用
                if (path == null) {
                    return;
                }
                jTree_folderlist.setSelectionPath(path);
                jPopupMenu_treemenu.show(jTree_folderlist, evt.getX(), evt.getY());
            }
            return;

        }
        if (evt.getClickCount() == 1) {
            //选中节点，列出权限文件

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree_folderlist.getLastSelectedPathComponent();
            if (node == null) {
                return;
            }
            File _f = (File) node.getUserObject();
            String xmlpath = _f.getAbsolutePath() + "\\cvs\\fileattr.xml";
            File _cvscontrolf = new File(xmlpath);


            if (_cvscontrolf.isFile()) {
                //                System.out.println("!!!!!!!!!!!!!");
                String xml_content = FilePlus.ReadTextFileToStringLn(xmlpath);
                jTextArea_xmlcontent.setText(xml_content);


            } else {
                return;
            }
            //解析xml
            try {
                SAXReader reader = new SAXReader();
                Document doc = reader.read(_cvscontrolf);
                Element rootelement = doc.getRootElement();
                List acls = doc.selectNodes("/fileattr/directory/acl");
                DefaultTableModel model = (DefaultTableModel) jTable_test.getModel();
                clearTable();
                //循环每个ACL区段


                for (Iterator it = acls.iterator(); it.hasNext();) {
                    CvsAcl ca = new CvsAcl();//控制块对象
                    Element ele = (Element) it.next();
                    String username = ele.attributeValue("user");
//                    System.out.println("username:" + username);
                    //加到控制块对象中的username中。
                    ca.username = username;
                    List eles = ele.elements();
                    for (Iterator it1 = eles.iterator(); it1.hasNext();) {
                        Element object = (Element) it1.next();
                        //遍历每个权限,添加到控制块对象
                        String aclname = object.getName().trim();
                        if (aclname.equalsIgnoreCase("all")) {
                            if (object.attributeValue("deny") == null) {
                                ca.set("all");
                            } else {
                                ca.set("deny");
                            }
                        } else {
                            ca.set(aclname);
                        }
                    }
                    //在表中加入
                    model.addRow(ca.toVector());
                    //                Object[] a = {"", false, false, false, false, false, false, false};



                }

            } catch (DocumentException ex) {
                Logger.getLogger(CvsTreeView.class.getName()).log(Level.SEVERE, null, ex);
            }



        }
        if (evt.getClickCount() >= 2) {
//            return;

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree_folderlist.getLastSelectedPathComponent();
            File _f = (File) node.getUserObject();
//            System.out.println(node.getUserObject().getClass());
//            System.out.println(node);
            node.removeAllChildren();

            int count = fillFileNode(_f, node);
            jTree_folderlist.updateUI();
//            System.out.println("树高度"+jTree_folderlist.getRowHeight());

            if (count > 0) {
                jTree_folderlist.expandRow(jTree_folderlist.getLeadSelectionRow());
            }
//            jTree_folderlist.validate();
//            jTree_folderlist.updateUI();

        }
    }//GEN-LAST:event_jTree_folderlistMouseClicked

    private void jButton_deleteRowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_deleteRowActionPerformed

        DefaultTableModel model = (DefaultTableModel) jTable_test.getModel();


        if (jTable_test.getSelectedRow() > -1) {
            model.removeRow(jTable_test.getSelectedRow());


        }
    }//GEN-LAST:event_jButton_deleteRowActionPerformed

    private void jButton_clearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_clearActionPerformed
        clearTable();

    }//GEN-LAST:event_jButton_clearActionPerformed
    private void jButton_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_saveActionPerformed
       DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree_folderlist.getLastSelectedPathComponent();


        if (node == null) {
            return;


        }
        File _f = (File) node.getUserObject();
//        JOptionPane.showConfirmDialog(jSplitPane1, _f.getAbsolutePath());
        String xmlpath = _f.getAbsolutePath() + "\\cvs\\fileattr.xml";
        File _cvscontrolf = new File(xmlpath);
        File _cvscontrolfbak = new File(xmlpath + ".bak");


        try {
            //备份原始文件
            FilePlus.CopyFile(_cvscontrolf, _cvscontrolfbak);



        } catch (IOException ex) {
            Logger.getLogger(CvsTreeView.class.getName()).log(Level.SEVERE, null, ex);
        }

        DefaultTableModel model = (DefaultTableModel) jTable_test.getModel();
        Vector vall = model.getDataVector();
        List<CvsAcl> cvssacllist = new ArrayList<CvsAcl>();


        for (Iterator it = vall.iterator(); it.hasNext();) {
            Vector v1 = (Vector) it.next();
            CvsAcl ca = new CvsAcl(v1);
            cvssacllist.add(ca);


        }

        try {
            Document document = DocumentHelper.createDocument();
            Element root = document.addElement("fileattr");
            Element dir = root.addElement("directory");
            //添加owner
            Element owner = dir.addElement("owner");
            owner.setText("root");
            for (Iterator<CvsAcl> it = cvssacllist.iterator(); it.hasNext();) {
                CvsAcl cvsAcl = it.next();
                Element ca = cvsAcl.getXmlElement();
                dir.add(ca);
            }
            XMLWriter writer = new XMLWriter(new FileWriter(_f.getAbsolutePath() + "\\cvs\\fileattr.xml"));
            writer.write(document);
            writer.close();
            //            System.out.println(doc.asXML());



        } catch (IOException ex) {
            Logger.getLogger(CvsTreeView.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_jButton_saveActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        try {
            // TODO add your handling code here:
            //保存路径
            String path = jTextField_cvsrootfolder.getText();
            ObjectOutputStream out = null;
            out = new ObjectOutputStream(new FileOutputStream(STORE_FILE));
            out.writeObject(path);
        } catch (IOException ex) {
            Logger.getLogger(CvsTreeView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formWindowClosing

    private void jMenuItem_openFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_openFolderActionPerformed
//            JOptionPane.showConfirmDialog(jSplitPane1, "本 打开目录 功能暂未实现，留待下一版本想起来再说");
        String path = ((File) ((DefaultMutableTreeNode) jTree_folderlist.getLastSelectedPathComponent()).getUserObject()).getAbsolutePath();

        jTree_folderlist.getLastSelectedPathComponent();
        try {
            Process p = Runtime.getRuntime().exec("explorer.exe " + path);
        } catch (IOException ex) {
            Logger.getLogger(CvsTreeView.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_jMenuItem_openFolderActionPerformed

    private void jMenuItem_newFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem_newFolderActionPerformed
        if (JOptionPane.showConfirmDialog(jTree_folderlist, "本功能不算完善，可能会引起一些小问题，确定继续？") != JOptionPane.YES_OPTION) {
            return;
        }
        String newname = JOptionPane.showInputDialog(jTree_folderlist, "输入新目录名称");
        if (newname.equalsIgnoreCase("cvs")) {
            JOptionPane.showMessageDialog(jTree_folderlist, "你在和我开国际玩笑？");
        }
        String rootpath = ((File) ((DefaultMutableTreeNode) jTree_folderlist.getLastSelectedPathComponent()).getUserObject()).getAbsolutePath();
        String newpath = rootpath + "/" + newname;
        File newdir = new File(newpath);
        //建立目录阶段
        if (newdir.exists()) {
            if (newdir.isFile()) {
                return;
            } else {
                int a = JOptionPane.showConfirmDialog(jTree_folderlist, "已存在同名的目录,可能会覆盖现在的项目。是否继续？", "提示", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                if (a != JOptionPane.YES_OPTION) {
                    return;
                }
            }
        } else {
            newdir.mkdirs();
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree_folderlist.getLastSelectedPathComponent();
            ((DefaultTreeModel) jTree_folderlist.getModel()).insertNodeInto(
                    new DefaultMutableTreeNode((new File(newpath))), node, node.getChildCount());
        }
        //建立下级结构
        (new File(newpath + "/CVS")).mkdirs();
        if(new File(newpath + "/CVS/fileattr.xml").exists()){
            int a = JOptionPane.showConfirmDialog(jTree_folderlist, "已存在控制文件,会覆盖为空规则是否继续？", "提示", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                if (a != JOptionPane.YES_OPTION) {
                    return;
                }
        }
        FilePlus.writeText(newpath + "/CVS/fileattr.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><fileattr><directory><owner>root</owner></directory></fileattr>");
        FilePlus.writeText(newpath + "/" + newname + ".txt,v", "head\t1.1;\naccess;\nsymbols;\nlocks; strict;\ncomment\t@# @;\n\n\n1.1\ndate\t2010.12.13.03.59.30;\tauthor root;\tstate Exp;\nbranches;\nnext\t;\ndeltatype\ttext;\nkopt\tkv;\npermissions\t666;\ncommitid\tbcc4d059a22646c;\nfilename\t" + newname + ".txt;\n\n\ndesc\n@@\n\n\n1.1\nlog\n@no message\n@\ntext\n@@\n");

    }//GEN-LAST:event_jMenuItem_newFolderActionPerformed

    private void jTabbedPane_xmlcontentStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPane_xmlcontentStateChanged
        // TODO add your handling code here:
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree_folderlist.getLastSelectedPathComponent();
            if (node == null) {
                return;
            }
            File _f = (File) node.getUserObject();
            String xmlpath = _f.getAbsolutePath() + "\\cvs\\fileattr.xml";
            File _cvscontrolf = new File(xmlpath);


            if (_cvscontrolf.isFile()) {
                //                System.out.println("!!!!!!!!!!!!!");
                String xml_content = FilePlus.ReadTextFileToStringLn(xmlpath);
                jTextArea_xmlcontent.setText(xml_content);


            } else {
                return;
            }
            //解析xml
            try {
                SAXReader reader = new SAXReader();
                Document doc = reader.read(_cvscontrolf);
                Element rootelement = doc.getRootElement();
                List acls = doc.selectNodes("/fileattr/directory/acl");
                DefaultTableModel model = (DefaultTableModel) jTable_test.getModel();
                clearTable();
                //循环每个ACL区段


                for (Iterator it = acls.iterator(); it.hasNext();) {
                    CvsAcl ca = new CvsAcl();//控制块对象
                    Element ele = (Element) it.next();
                    String username = ele.attributeValue("user");
//                    System.out.println("username:" + username);
                    //加到控制块对象中的username中。
                    ca.username = username;
                    List eles = ele.elements();
                    for (Iterator it1 = eles.iterator(); it1.hasNext();) {
                        Element object = (Element) it1.next();
                        //遍历每个权限,添加到控制块对象
                        String aclname = object.getName().trim();
                        if (aclname.equalsIgnoreCase("all")) {
                            if (object.attributeValue("deny") == null) {
                                ca.set("all");
                            } else {
                                ca.set("deny");
                            }
                        } else {
                            ca.set(aclname);
                        }
                    }
                    //在表中加入
                    model.addRow(ca.toVector());
                    //                Object[] a = {"", false, false, false, false, false, false, false};



                }

            } catch (DocumentException ex) {
                Logger.getLogger(CvsTreeView.class.getName()).log(Level.SEVERE, null, ex);
            }

    }//GEN-LAST:event_jTabbedPane_xmlcontentStateChanged

    /**
     * 填充jtree的node
     * @param f_rootdir
     * @param rootnode
     * @return
     */
    static int fillFileNode(File f_rootdir, DefaultMutableTreeNode rootnode) {
        File[] fs = f_rootdir.listFiles(FilePlus.cvsFather_DirOnlyFilter);


        for (int i = 0; i
                < fs.length; i++) {
            File f = fs[i];
            DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
            rootnode.add(child);


        }
        return fs.length;


    }

    /**
     * 清空表
     */
    void clearTable() {
        for (int index = jTable_test.getModel().getRowCount() - 1; index
                >= 0; index--) {
            DefaultTableModel testmodel = (DefaultTableModel) jTable_test.getModel();
            testmodel.removeRow(index);


        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");


        } catch (ClassNotFoundException ex) {
        } catch (InstantiationException ex) {
        } catch (IllegalAccessException ex) {
        } catch (UnsupportedLookAndFeelException ex) {
        }
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
//                new CvsTreeView().setVisible(true);
                CvsTreeView ctv = new CvsTreeView();

//                ctv.gpstream = new GUIPrintStream(System.out, ctv.jTextArea_output);
//                System.setOut(ctv.gpstream);
                //初始化目录

                String rootdir = ctv.jTextField_cvsrootfolder.getText();
                File f = new File(STORE_FILE);
                if (f.isFile()) {
                    try {
                        FileInputStream fis = new FileInputStream(f);
                        ObjectInputStream in = new ObjectInputStream(fis);
                        rootdir = (String) in.readObject();
                        ctv.jTextField_cvsrootfolder.setText(rootdir);
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(CvsTreeView.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(CvsTreeView.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                File f_rootdir = new File(rootdir);


                if (f_rootdir.isDirectory()) {

                    DefaultMutableTreeNode rootnode = new DefaultMutableTreeNode(f_rootdir);
                    fillFileNode(
                            f_rootdir, rootnode);
                    DefaultTreeModel model = new DefaultTreeModel(rootnode);
                    ctv.jTree_folderlist.setModel(model);
                    WindowsTreeCellRenderer cellRenderer = (WindowsTreeCellRenderer) ctv.jTree_folderlist.getCellRenderer();
//                    TreeCellRenderer cellRenderer =  ctv.jTree_folderlist.getCellRenderer();
//                    MotifTreeCellRenderer cellRenderer = (MotifTreeCellRenderer) ctv.jTree_folderlist.getCellRenderer();
//                    cellRenderer.setLeafIcon(new ImageIcon("..\\icons\\leaf.gif"));
//                    cellRenderer.setOpenIcon(new ImageIcon("..\\icons\\open.gif"));
//                    cellRenderer.setClosedIcon(new ImageIcon("..\\icons\\close.gif"));

                    cellRenderer.setFont(new Font("宋体", Font.PLAIN, 12));//设置字体.
                    cellRenderer.setBackgroundNonSelectionColor(Color.white);
                    cellRenderer.setBackgroundSelectionColor(Color.yellow);
                    cellRenderer.setBorderSelectionColor(Color.red);
                    /*设置选时或不选时，文字的变化颜色
                     */
                    cellRenderer.setTextNonSelectionColor(Color.black);
                    cellRenderer.setTextSelectionColor(Color.blue);




                }

                ctv.setVisible(true);




            }
        });






    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_clear;
    private javax.swing.JButton jButton_deleteRow;
    private javax.swing.JButton jButton_find;
    private javax.swing.JButton jButton_go;
    private javax.swing.JButton jButton_insertRow;
    private javax.swing.JButton jButton_save;
    private javax.swing.JMenuItem jMenuItem_newFolder;
    private javax.swing.JMenuItem jMenuItem_openFolder;
    private javax.swing.JPanel jPanel_properties;
    private javax.swing.JPanel jPanel_table;
    private javax.swing.JPanel jPanel_tableControl;
    private javax.swing.JPopupMenu jPopupMenu_treemenu;
    private javax.swing.JScrollPane jScrollPane_jtree;
    private javax.swing.JScrollPane jScrollPane_table;
    private javax.swing.JScrollPane jScrollPane_xmlcontent;
    private javax.swing.JSplitPane jSplitPane_holder;
    private javax.swing.JTabbedPane jTabbedPane_xmlcontent;
    private javax.swing.JTable jTable_test;
    private javax.swing.JTextArea jTextArea_xmlcontent;
    private javax.swing.JTextField jTextField_cvsrootfolder;
    private javax.swing.JToolBar jToolBar_menu;
    private javax.swing.JTree jTree_folderlist;
    // End of variables declaration//GEN-END:variables
}
